﻿using System.Windows;
using System.Windows.Controls;

namespace MapleLeaf.Client.Controls {

    public class PasswordBoxHost : ContentControl {
        public string Password {
            get => (string)GetValue(PasswordProperty);
            set {
                SetValue(PasswordProperty, value);
                if (Content != null && (Content as PasswordBox).Password != Password) {
                    (Content as PasswordBox).Password = Password;
                }
            }
        }


        protected override void OnContentChanged(object oldContent, object newContent) {
            if (oldContent != null) {
                (oldContent as PasswordBox).Loaded -= PasswordBoxHost_Loaded;
                (oldContent as PasswordBox).PasswordChanged -= OnPasswordChanged;
            }
            base.OnContentChanged(oldContent, newContent);
            if (newContent != null) {
                (newContent as PasswordBox).Loaded += PasswordBoxHost_Loaded;
            }
        }


        private void PasswordBoxHost_Loaded(object sender, RoutedEventArgs e) {
            (sender as PasswordBox).Password = Password;
            (sender as PasswordBox).PasswordChanged += OnPasswordChanged;
        }


        private void OnPasswordChanged(object sender, RoutedEventArgs e) {
            if ((sender as PasswordBox).IsFocused && (sender as PasswordBox).Password != Password) {
                Password = (sender as PasswordBox).Password;
            }
        }


        public PasswordBoxHost() {
     
        }

        static PasswordBoxHost() {
            PasswordProperty = DependencyProperty.Register("Password", typeof(string), typeof(PasswordBoxHost));
        }


        public static readonly DependencyProperty PasswordProperty;
    }
}
